package kr.saeildamil.androidforstudy2.ch24;

import kr.saeildamil.androidforstudy2.R;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
import android.view.animation.BounceInterpolator;

public class AnimationView extends View {
	Ball mBall;
	Paint mPaint;
	ObjectAnimator mRight;
	ObjectAnimator mDown;
	ObjectAnimator mLarge;
	
	public AnimationView(Context context) {
		super(context);
		init();
	}
	
	public AnimationView(Context context, boolean status){
		super(context);
		init();
		mRight = ObjectAnimator.ofInt(mBall, "x", 100, 460);
		mRight.setDuration(2000);
		mRight.addUpdateListener(listener);
		
		mDown = ObjectAnimator.ofInt(mBall, "y", 50, 300);
		mDown.setDuration(2000);
		mDown.addUpdateListener(listener);
		
		mLarge = ObjectAnimator.ofInt(mBall, "rad", 20, 50);
		mLarge.setDuration(2000);
		mLarge.addUpdateListener(listener);
	}
	
	public void StartAnimating(int id){
		mBall.setX(100);
		mBall.setY(50);
		mBall.setRad(20);
		
		AnimatorSet set = new AnimatorSet();
		
		switch (id) {
		case R.id.btn1:
			set.playSequentially(mRight, mDown, mLarge);
			break;
		case R.id.btn2:
			set.playSequentially(mDown, mRight, mLarge);
			break;
		case R.id.btn3:
			set.playTogether(mRight, mDown, mLarge);
			break;
		case R.id.btn4:
			set.play(mRight).with(mLarge).before(mDown);
		}
		set.start();
	}
	
	AnimatorUpdateListener listener = new AnimatorUpdateListener() {
		public void onAnimationUpdate(ValueAnimator animation) {
			invalidate();
		}
	};
	
	public void init(){
		mBall = new Ball();
		mBall.setX(100);
		mBall.setY(200);
		mBall.setRad(20);
		
		mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
		mPaint.setColor(Color.MAGENTA);	
	}
	
	public void startAnimating(){
		ObjectAnimator animator = ObjectAnimator.ofInt(mBall, "x", 100, 460);
		// x 에는 반드시 get,set method 가 있어야 함;
		animator.setDuration(2000);
		animator.setInterpolator(new BounceInterpolator());
		animator.addUpdateListener(new AnimatorUpdateListener() {

			public void onAnimationUpdate(ValueAnimator animation) {
				invalidate();
			}
		});
		
		animator.start();
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		canvas.drawCircle(mBall.getX(), mBall.getY(), mBall.getRad(), mPaint);
	}
}
